<template>
  <div class="password-container">
    <div class="password-content">
      <el-form ref="formRef" :model="registerStore.userInfo" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="密码:" prop="password">
              <el-input
                v-model="registerStore.userInfo.password"
                type="password"
                show-password
                placeholder="请输入密码"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="确认密码:" prop="confirmPassword">
              <el-input
                v-model="registerStore.userInfo.confirmPassword"
                show-password
                type="password"
                placeholder="请确认密码"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="password-footer">
      <el-button type="primary" @click="handlerPrevStep">上一步</el-button>
      <el-button type="primary" @click="handlerNextStep">下一步</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useRegisterStore } from "@/store/modules/register.store";
const registerStore = useRegisterStore();
const router = useRouter();

const formRef = ref();

// 自定义验证函数
const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  console.log(rule);

  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== registerStore.userInfo.password) {
    callback(new Error("两次输入的密码不一致!"));
  } else {
    callback(); // 验证通过
  }
};

const rules = reactive({
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 8, max: 16, message: "长度在8-16个字符", trigger: "blur" },
  ],
  confirmPassword: [{ required: true, validator: validateConfirmPassword, trigger: "blur" }],
});

function handlerPrevStep() {
  emit("prev");
}

function handlerNextStep() {
  formRef.value.validate((valid: any) => {
    if (valid) {
      // 触发完成事件，传递当前步骤数据
      emit("complete", { success: true });
    }
  });
}

const emit = defineEmits(["complete", "prev"]);

onMounted(() => {
  registerStore.userInfo.password = "";
  registerStore.userInfo.confirmPassword = "";
  if (!registerStore.userInfo.userAccount) {
    router.push("/register/1");
  }
});
</script>

<style lang="scss" scoped>
.password-container {
  padding: 20px;
  .password-content {
    min-height: 600px;
  }
  .password-footer {
    display: flex;
    justify-content: space-around;
  }
}
</style>
